package graph.day16;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Scanner;

public class Kruskal {

    static class Edge {
        int l, r, val;

        Edge(int l, int r, int val) {
            this.l = l;
            this.r = r;
            this.val = val;
        }
    }

    private static int[] father;

    public static void init(int n) {
        father = new int[n];
        for (int i = 0; i < n; i++) {
            father[i] = i;
        }
    }

    public static int find(int x) {
        if (father[x] == x) {
            return x;
        }
        return father[x] = find(father[x]);
    }

    public static void join(int x, int y) {
        int fx = find(x);
        int fy = find(y);
        if (fx != fy) {
            father[fx] = fy;
        }
    }

    public static boolean isSame(int x, int y) {
        x = find(x);
        y = find(y);
        return x == y;
    }

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int v = sc.nextInt();
        int e = sc.nextInt();
        List<Edge> edges = new ArrayList<>();
        int result = 0;

        for (int i = 0; i < e; i++) {
            int v1 = sc.nextInt();
            int v2 = sc.nextInt();
            int val = sc.nextInt();
            edges.add(new Edge(v1, v2, val));
        }

        edges.sort(Comparator.comparingInt(a -> a.val));
        init(v);

        for (Edge edge : edges) {
            int x = find(edge.l);
            int y = find(edge.r);

            if (x != y) {
                result += edge.val;
                join(x, y);
            }
        }
        System.out.println(result);
    }
}
